package com.central.scheduler.api.controller;

import com.central.common.annotation.LoginUser;
import com.central.common.annotation.RequiredPermission;
import com.central.common.constant.PermissionConstants;
import com.central.common.model.*;
import com.central.common.utils.UserRoleUtil;
import com.central.scheduler.api.service.IQueueService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Tindy
 * @date 2021/6/24
 * @describe
 */
@RestController
@Api(tags = "queue模块api")
@Slf4j
@RequestMapping("/queue")
public class QueueController {
    @Autowired
    private IQueueService queueService;



    @ApiOperation(value = "新增或修改queue")
    @PostMapping("/addOrUpdate")
    @RequiredPermission(PermissionConstants.SYS_ADMIN)
    public Result addOrUpdate(@RequestBody QueueInfo queueInfo) {
        try {
            //这里配置只是为任务执行时查询队列名所用，管理员还需要到集群平台去添加真实的队列并配置动态资源
            queueService.saveOrUpdate(queueInfo);
            return Result.succeed("操作成功");
        } catch (Exception ex) {
            log.error("queue-add/update-error", ex);
            return Result.failed("操作失败");
        }
    }

    @ApiOperation(value = "查询queue列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer")
    })
    @GetMapping("/findQueues")
    public PageResult<QueueInfo> findQueues(@ApiIgnore @LoginUser SysUser user, @RequestParam Map<String, Object> params) {
        if (UserRoleUtil.checkSysAdmin(user.getRoles())) {
            return queueService.findQueues(params);
        } else {
            params.put("proId",user.getCurrentProjectId());
            return queueService.findQueuesByPro(params,user.getCurrentProjectId());
        }
    }

    @ApiOperation(value = "配置项目")
    @PostMapping("/setPros")
    @RequiredPermission(PermissionConstants.SYS_ADMIN)
    public Result setPros(Long queueId,@RequestBody Set<Long> proIds) {
        try {
            //这里配置只是为任务执行时查询队列名所用，管理员还需要到集群平台去添加队列用户组
            queueService.setPros(queueId,proIds);
            return Result.succeed("操作成功");
        } catch (Exception ex) {
            log.error("scheduler-setPros-error", ex);
            return Result.failed("操作失败");
        }
    }

    @ApiOperation(value = "获取queue所有项目")
    @GetMapping("/getPros")
    public List<SysProject> getPros(Long queueId) {
        return queueService.getPros(queueId);
    }
}
